import { ref, onBeforeUnmount } from "vue";

export const useLatest = (value) => {
  const refa = ref(value);
  refa.value = value;

  return refa;
};

export const useInterval = (fn, delay, options = { immediate: false }) => {
  const { immediate } = options;

  const fnRef = useLatest(fn);
  const timerRef = ref(null);

  const clear = () => {
    if (timerRef.value) {
      timerRef.value = null;
      clearInterval(timerRef.value);
    }
  };

  const opentask = () => {
    if (delay < 0) {
      return;
    }
    if (immediate) {
      fnRef.value();
    }
    timerRef.value = setInterval(() => {
      fnRef.value();
    }, delay);
  };

  opentask();

  onBeforeUnmount(clear);

  return clear;
};
